package com.adlotto2.android.activity.mypage;

import java.util.ArrayList;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.adlotto2.android.R;
import com.adlotto2.android.activity.mypage.adapter.LottoAdChangeListAdapter;
import com.adlotto2.android.common.BaseActivity;
import com.adlotto2.android.cronos.data.CNLottoAdChangeListData;
import com.adlotto2.android.cronos.datahandler.CNBaseDataParser;
import com.adlotto2.android.cronos.datahandler.CNBaseDataSet;
import com.adlotto2.android.cronos.datahandler.CNResultSet;
import com.adlotto2.android.cronos.http.CNLottoAdApiSetEx;
import com.adlotto2.android.cronos.parser.CNLottoChangeListParser;
import com.adlotto2.android.util.ApplicationUtils;
import com.adlotto2.android.util.CNCronosLog;

/**
 * MyPage - 전환내역 확인하기 Activity
 * @author Administrator
 *
 */
public class LottoAdMypageChangeListActivity extends BaseActivity{
	private Context mContext;
	
	/** 요청 페이지 Number **/
	private int mPageNum = 1;
	/** 데이터 셋 유/무 체크 플래그 **/
	private boolean isDataSet = false;
	/** 다음페이지 유/무 체크 플래그 **/
	private boolean isNextPage = false;
	/** 비동기 작업수행 여부 체크 플래그 **/
	private boolean mNetAsyncing = false;
	/** 리스트의 마지막 포지션값 **/
	private int mListLastPosition = 0;
	
	/** 전환내역 리스트뷰 **/
	private ListView mListView;
	private LottoAdChangeListAdapter mListAdapter;
	private ArrayList<CNBaseDataSet> mDataSetList;
	
	/** 총 누적 적립금액 **/
	private TextView mNujukTv;
	/** 전환 신청금액 **/
	private TextView mAskTv;
	/** 이체 완료금액 **/
	private TextView mPaidTv;
	/** 이체신청 가능금액 **/
	private TextView mUsableTv;
	
	private String mNujukMoney, mAskMoney, mPaidMoney = "", mUsableMoney = "";
	
	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_menu_mypage_changelist;
	}

	@Override
	protected void onInit() {
		this.mContext = LottoAdMyPageGroupActivity.mContext;
	}
	
	private void buildComponent(){
		mListView = (ListView) findViewById(R.id.list_view);
		
		mNujukTv = (TextView) findViewById(R.id.textView_nujuk);
		mAskTv = (TextView) findViewById(R.id.textView_ask);
		mPaidTv = (TextView) findViewById(R.id.textView_paid);
		mUsableTv = (TextView) findViewById(R.id.textView_usable);
		
		mListAdapter = new LottoAdChangeListAdapter(mContext);
		mListView.setAdapter(mListAdapter);
		
		Intent intent = getIntent();
		
		mNujukMoney = intent.getStringExtra("nujuk");
		mAskMoney = intent.getStringExtra("ask");
		mPaidMoney = intent.getStringExtra("paid");
		mUsableMoney = intent.getStringExtra("usable");
		
		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View convertView, int position, long arg3) {
				CNLottoAdChangeListData data = (CNLottoAdChangeListData) mDataSetList.get(position);
				CNCronosLog.d("position =================>" + position);
				CNCronosLog.d("data.askDate : "+data.askDate);
				CNCronosLog.d("data.paidDate : "+data.paidDate);
				CNCronosLog.d("data.askMoney : "+data.askMoney);
				CNCronosLog.d("data.accountName : "+data.accountName);
				CNCronosLog.d("data.bankName : "+data.bankName);
				CNCronosLog.d("data.accountNumber : "+data.accountNumber);
				CNCronosLog.d("data.comment : "+data.comment);
				
				Intent intent = new Intent(mContext, LottoAdMyPageChangeListDetailActivity.class);
				intent.putExtra("number", String.valueOf(mListAdapter.getCount() - position));
				intent.putExtra("askDate", data.askDate.split(" ")[0].substring(2, data.askDate.split(" ")[0].length()));
				if(data.paidDate !=null &&  !data.paidDate.equals("")&& data.paidDate.length() > 0){
					intent.putExtra("paidDate", data.paidDate.split(" ")[0].substring(2, data.paidDate.split(" ")[0].length()));
				} else {
					intent.putExtra("paidDate", "");
				}
				intent.putExtra("isChange", data.isChange);
				
				intent.putExtra("askMoney", data.askMoney);
				
				intent.putExtra("accountName", data.accountName);
				intent.putExtra("bankName", data.bankName);
				intent.putExtra("accountNumber", data.accountNumber);
				intent.putExtra("comment", data.comment);
				
				intent.putExtra("nujuk", mNujukMoney);
				intent.putExtra("ask", mAskMoney);
				intent.putExtra("paid", mPaidMoney);
				intent.putExtra("usable", mUsableMoney);
				
				((LottoAdMyPageGroupActivity)getParent()).startChildActivity("MyPageChageListDetailActivity", intent);
			}
		});
		
		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView abslistview, int i) {
				try
		        { 
					if(isDataSet)
					{
						int mLastPosition = abslistview.getLastVisiblePosition();
						CNCronosLog.d("mLastPosition : "+ mLastPosition);
						if((mLastPosition == mListLastPosition - 1) && isNextPage && !mNetAsyncing){ 
							mPageNum = mPageNum + 1;
			            	mNetAsyncing = true;
			            	onRequestData();
			            }
					}
		        }catch(Exception e){ 
		        	
		        }
			}
			
			@Override
			public void onScroll(AbsListView abslistview, int i, int j, int k) {
				
			}
		});
		
		onRequestData();
	}
	
	private void parsingChangeList(Element xmlObject) throws Exception{
		
		mDataSetList = new ArrayList<CNBaseDataSet>();
		
		CNBaseDataParser parser = new CNLottoChangeListParser();
		CNResultSet resultSet = parser.parse(xmlObject);
		ArrayList<CNBaseDataSet> dataSet = null;
		
		if (resultSet != null)
		{
			dataSet = resultSet.getDataSetList();
			if (dataSet != null)
			{
				int count = dataSet.size();		
				CNCronosLog.d("DataSet.size():" + count);
				for (int i = 0; i < count; i++)
				{
					CNLottoAdChangeListData data = (CNLottoAdChangeListData) dataSet.get(i);
					
					CNCronosLog.d("================="+i+"================");
					CNCronosLog.d("data.askDate : "+data.askDate);
					CNCronosLog.d("data.paidDate : "+data.paidDate);
					CNCronosLog.d("data.askMoney : "+data.askMoney);
					CNCronosLog.d("data.accountName : "+data.accountName);
					CNCronosLog.d("data.bankName : "+data.bankName);
					CNCronosLog.d("data.accountNumber : "+data.accountNumber);
					CNCronosLog.d("data.comment : "+data.comment);
					
					mDataSetList.add(data);
				}
			}
			
			isNextPage = mDataSetList.size() < resultSet.getTotalCount();
			isDataSet = mDataSetList.size() > 0;
			mListLastPosition =  mDataSetList.size();
		}
		
		mListAdapter.setDataSetList(mDataSetList);
		mListAdapter.notifyDataSetChanged();
		
		mNetAsyncing = false;
		
		updateUI(mNujukMoney + "원", mAskMoney + "원", mPaidMoney + "원", mUsableMoney + "원");
	}
	
	private void updateUI(String nujukMoney, String askMoney, String paidMoney, String usableMoney){
		mNujukTv.setText(nujukMoney);
		mAskTv.setText(askMoney);
		mPaidTv.setText(paidMoney);
		mUsableTv.setText(usableMoney);
	}
	
	@Override
	public String onGetAsyncRequestUrl() {
		CNCronosLog.d("onGetAsyncRequestUrl()");
		String url = null;
		
		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		url = MnetGlobalApiSetEx.getTransferListUrl(mContext, ApplicationUtils.getPhoneNumber(mContext), mPageNum);
		
		CNCronosLog.d("onGetAsyncRequestUrl", "url : "+url);
		
		return url;
	}
	
	@Override
	public void onAsyncCancelRequest() 
	{
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncCancelRequest()");
	}

	@Override
	public void onAsyncDataError(Element xmlObject, String errorMessage)
	{
		super.hideLoadingDialog();
		
		NodeList rcodeNode = xmlObject.getElementsByTagName("rcode");
		String rcode = rcodeNode.item(0).getFirstChild().getNodeValue();
		
		if(!"RET0002".equals(rcode)){
			ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), errorMessage);
		} else {
			updateUI(mNujukMoney + "원", mAskMoney + "원", mPaidMoney + "원", mUsableMoney + "원");
		}
	}

	@Override
	public void onAsyncPreRequest()
	{
		super.showLoadingDialog(mContext);
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject)
	{
		super.hideLoadingDialog();
		
			
		try {
				parsingChangeList(xmlObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onAsyncRequestError(int errorNumber) {
		super.hideLoadingDialog();
		
		ApplicationUtils.showOkDialog(mContext,0,getString(R.string.popup_alert), ApplicationUtils.getErrorMessage(mContext, errorNumber));
	}

	@Override
	protected void onResume() {
		super.onResume();
		buildComponent();
	}
	
	@Override
	public void onBackPressed() {
		((LottoAdMyPageGroupActivity)getParent()).onBackPressed();
	}
}
